package com.gpframework.module.ctn.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpframework.common.exception.CustomException;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.ctn.domain.*;
import com.gpframework.module.ctn.domain.req.GpCtnLoadedAdd;
import com.gpframework.module.ctn.domain.req.GpCtnLoadedReq;
import com.gpframework.module.ctn.domain.req.GpCtnLoadedUpdate;
import com.gpframework.module.ctn.domain.vo.GpCtnLoadedExcel;
import com.gpframework.module.ctn.domain.vo.GpCtnLoadedVo;
import com.gpframework.module.ctn.mapper.GpCtnLoadedMapper;
import com.gpframework.module.ctn.service.IGpCtnLoadedService;
import com.gpframework.module.ctn.service.IGpCtnOrderService;
import com.gpframework.module.ctn.service.IGpReceiptGoodsService;
import com.gpframework.module.ctn.service.IGpSackInformationService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName GpCtnLoaded
 * @Author gpframework
 * @Date 2024-01-08
 * @Version 1.0.0
 * @Description 装柜信息填写装柜录入Service业务层处理
 */
@Service
public class GpCtnLoadedServiceImpl extends ServiceImpl<GpCtnLoadedMapper, GpCtnLoaded> implements IGpCtnLoadedService {


    @Autowired
    private GpPackagesInformationServiceImpl iGpPackagesInformationService;
    @Autowired
    private IGpCtnLoadedService iGpCtnLoadedService;

    @Autowired
    private IGpCtnOrderService iGpCtnOrderService;
    @Autowired
    private IGpReceiptGoodsService iGpReceiptGoodsService;

    @Autowired
    private IGpSackInformationService iGpSackInformationService;

    /**
     * @Description 查询列表返回VO 用于返回给前端的列表接口
     * @Author gpframework
     * @Date 2024-01-08
     * @Param [lqw]
     * @Return List<GpCtnLoadedVo>
     */
    @Override
    public List<GpCtnLoadedVo> listVo(QueryWrapper<GpCtnLoaded> lqw) {
        List<GpCtnLoadedVo> list = this.baseMapper.listVo(lqw);
        //for (GpCtnLoadedVo vo : list) {
        //    vo.setPackagesInformationList(iGpPackagesInformationService.listVo(new QueryWrapper<GpPackagesInformation>().eq("gp.ctn_order_id", vo.getId()).eq("gp.del_status", YesNoEnum.NO.getKey())));
        //}
        return list;
    }


    /**
     * @Description 通过查询详情VO 用于返回给前端的列详情接口
     * @Author gpframework
     * @Date 2024-01-08
     * @Param [id]
     * @Return GpCtnLoadedVo
     */
    @Override
    public GpCtnLoadedVo getVoById(Long id) {
        GpCtnLoadedVo vo = this.baseMapper.getVo(id);
        //vo.setl(iGpCtnLoadedService.listVo(new QueryWrapper<GpCtnLoaded>().eq("gp.id", vo.getId()).eq("gp.del_status", YesNoEnum.NO.getKey())));
        //
        //for (GpCtnLoadedVo gpCtnLoadedVo : vo.getLoadedList()) {
        //    List<GpPackagesInformationVo> gpPackagesInformationVos = iGpPackagesInformationService.listVo(new QueryWrapper<GpPackagesInformation>().eq("gp.ctn_loaded_id", vo.getId()).eq("gp.del_status", YesNoEnum.NO.getKey()));
        //    gpCtnLoadedVo.setPackagesInformationList(gpPackagesInformationVos);
        //}

        return vo;
    }

    @Override
    public List<GpCtnLoadedExcel> gpCtnLoadedImport(List<GpCtnLoadedExcel> excelList, Long brandId, Long storeId) {
        //导入失败的列表
        List<GpCtnLoadedExcel> failureList = new ArrayList<>();
        //装柜信息填写装柜录入
        GpCtnLoaded gpCtnLoaded;

        for (int i = 0; i < excelList.size(); i++) {
            GpCtnLoadedExcel excel = excelList.get(i);
            if (StringUtils.isNull(excel)) {
                excel = new GpCtnLoadedExcel();
                excel.setSubscript(i + 1);
                excel.setMsg("读取数据失败");
                failureList.add(excel);
                continue;
            }
            gpCtnLoaded = Convert.convert(new TypeReference<GpCtnLoaded>() {
            }, excel);
            this.save(gpCtnLoaded);
        }
        return failureList;
    }



    /**
     * @param gpCtnLoadedExcels
     * @param isUpdateSupport
     * @return
     */
    @Override
    public String addbatchloadedNote(List<GpCtnLoadedExcel> gpCtnLoadedExcels, boolean isUpdateSupport) {
        if (StringUtils.isNull(gpCtnLoadedExcels) || gpCtnLoadedExcels.size() == 0) {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (GpCtnLoadedExcel gpCtnLoadedExcel : gpCtnLoadedExcels) {
            try {
                //查找数据
                GpReceiptGoods gpReceiptGoods = iGpReceiptGoodsService.getOne(new QueryWrapper<GpReceiptGoods>().eq("receipt_no", gpCtnLoadedExcel.getReceiptNo()));
                GpCtnOrder gpCtnOrder = iGpCtnOrderService.getOne(new QueryWrapper<GpCtnOrder>().eq("agent_ctn_no", gpCtnLoadedExcel.getAgentCtnNo()));
                if (StringUtils.isNull(gpReceiptGoods) && StringUtils.isNull(gpCtnOrder)) {
                    GpCtnLoaded gpCtnLoaded = Convert.convert(new TypeReference<GpCtnLoaded>() {
                    }, gpReceiptGoods);
                    gpCtnLoaded.setReceiptId(gpReceiptGoods.getId());
                    gpCtnLoaded.setCtnOrderId(gpCtnOrder.getId());
                    gpCtnLoaded.setBillNo(gpCtnOrder.getBillNo());
                    gpCtnLoaded.setCtnNo(gpCtnOrder.getCtnNo());
                    gpCtnLoaded.setSealNo(gpCtnOrder.getSealNo());
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、进仓单号 " + gpCtnLoadedExcel.getReceiptNo() + " 导入成功");
                    successMsg.append("<br/>" + successNum + "、货柜序货柜序号 " + gpCtnLoadedExcel.getAgentCtnNo() + " 导入成功");
                    iGpCtnLoadedService.save(gpCtnLoaded);
                } else if (isUpdateSupport) {
                    GpCtnLoaded gpCtnLoaded = Convert.convert(new TypeReference<GpCtnLoaded>() {
                    }, gpReceiptGoods);
                    gpCtnLoaded.setReceiptId(gpReceiptGoods.getId());
                    gpCtnLoaded.setCtnOrderId(gpCtnOrder.getId());
                    gpCtnLoaded.setBillNo(gpCtnOrder.getBillNo());
                    gpCtnLoaded.setCtnNo(gpCtnOrder.getCtnNo());
                    gpCtnLoaded.setSealNo(gpCtnOrder.getSealNo());
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、进仓单号 " + gpCtnLoadedExcel.getReceiptNo() + " 更新成功");
                    successMsg.append("<br/>" + successNum + "、货柜序货柜序号 " + gpCtnLoadedExcel.getAgentCtnNo() + " 更新成功");
                    iGpCtnLoadedService.updateById(gpCtnLoaded);
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、进仓单号 " + gpCtnLoadedExcel.getReceiptNo() + " 已存在");
                    successMsg.append("<br/>" + successNum + "、货柜序货柜序号 " + gpCtnLoadedExcel.getAgentCtnNo() + " 已存在");
                }

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、进仓单号 " + gpCtnLoadedExcel.getReceiptNo() + " 导入失败：";
                successMsg.append("<br/>" + successNum + "、货柜序货柜序号 " + gpCtnLoadedExcel.getAgentCtnNo() + " 导入失败");
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new CustomException(failureMsg.toString());
            } else {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            }
        }
        return successMsg.toString();

    }




    @Override
    public boolean addBatch(GpCtnLoadedUpdate gpCtnLoadedUpdate) {
        //List<Long> ids = gpCtnLoadedUpdate.getIds();
        //for (Long id : ids) {
        //    if (StringUtils.isNotEmpty(gpCtnLoadedUpdate.getLoadedList())) {
        //        //返回的list
        //        ArrayList<GpCtnLoaded> gpCtnLoadedList = new ArrayList<>();
        //        GpCtnLoadedVo gpCtnLoadedVo = this.getVoById(id);
        //        StringBuilder imageurls = new StringBuilder();
        //
        //        for (GpCtnLoadedVo ctnLoadedVo : gpCtnLoadedVo.getLoadedList()) {
        //            GpCtnLoaded gpCtnLoaded = Convert.convert(new TypeReference<GpCtnLoaded>() {
        //            }, ctnLoadedVo);
        //            GpCtnOrder ctnOrder = iGpCtnOrderService.getById(ctnLoadedVo.getCtnOrderId());
        //            GpReceiptGoods gpReceiptGoods = iGpReceiptGoodsService.getById(ctnLoadedVo.getReceiptId());
        //
        //            //柜里面绑定多个包 装柜操作
        //            BigDecimal totalPackWeight = null;
        //            for (Long packId : ctnLoadedVo.getPackIds()) {
        //                GpPackagesInformation gpPackagesInformation = iGpPackagesInformationService.getById(packId);
        //                gpPackagesInformation.setCtnLoadedId(ctnLoadedVo.getId());
        //                BigDecimal packWeight = gpPackagesInformation.getPackWeight();
        //
        //                //计算装柜的包重
        //                Long packagingNum = gpPackagesInformation.getPackagesPackagingNum();
        //                totalPackWeight = packWeight.multiply(BigDecimal.valueOf(packagingNum));
        //
        //                iGpPackagesInformationService.updateById(gpPackagesInformation);
        //            }
        //            //计算总重量=（散货*散货数量）+（打包数量*重量）
        //            BigDecimal sackWeight = gpReceiptGoods.getSackWeight();
        //            Long sackNum = gpReceiptGoods.getSackNum();
        //            BigDecimal totalWeight = sackWeight.multiply(BigDecimal.valueOf(sackNum)).add(totalPackWeight);
        //            gpCtnLoaded.setTotalWeight(totalWeight);
        //
        //            //保存订单信息
        //            gpCtnLoaded.setReceiptId(gpReceiptGoods.getId());
        //            gpCtnLoaded.setCustomer(gpReceiptGoods.getCustomer());
        //            gpCtnLoaded.setCustomerTel(gpReceiptGoods.getCustomerTel());
        //            gpCtnLoaded.setSupplier(gpReceiptGoods.getSupplier());
        //            gpCtnLoaded.setSupplierTel(gpReceiptGoods.getSupplierTel());
        //            gpCtnLoaded.setGoodsDescription(gpReceiptGoods.getGoodsDescription());
        //            gpCtnLoaded.setUnit(gpReceiptGoods.getUnit());
        //            gpCtnLoaded.setReceiptNo(gpReceiptGoods.getReceiptNo());
        //            gpCtnLoaded.setHoldOrNot(gpReceiptGoods.getHoldOrNot());
        //            gpCtnLoaded.setCbm(gpReceiptGoods.getCbm());
        //            gpCtnLoaded.setRemarks(gpReceiptGoods.getRemarks());
        //            gpCtnLoaded.setAgentCompany(gpReceiptGoods.getAgentName());
        //
        //            //保存订货柜信息
        //            gpCtnLoaded.setBillNo(ctnOrder.getBillNo());
        //            gpCtnLoaded.setCtnNo(ctnOrder.getCtnNo());
        //            gpCtnLoaded.setSealNo(ctnOrder.getSealNo());
        //            gpCtnLoaded.setCtnNo(ctnOrder.getCtnNo());
        //            gpCtnLoaded.setAgentCtnNo(ctnOrder.getAgentCtnNo());
        //            gpCtnLoaded.setCtnLoadTime(new Date());
        //
        //            //保存图片
        //            for (String imageurl : ctnLoadedVo.getLoadedPicturesList()) {
        //                imageurls.append(imageurl);
        //                imageurls.append(";");
        //            }
        //            //gpCtnLoaded.setLoadedPicturesList(imageurls.toString());
        //
        //            gpCtnLoaded.setCtnOrderId(ctnLoadedVo.getCtnOrderId());
        //            gpCtnLoaded.setReceiptId(ctnLoadedVo.getReceiptId());
        //            gpCtnLoadedList.add(gpCtnLoaded);
        //
        //        }
        //
        //        iGpCtnLoadedService.saveBatch(gpCtnLoadedList);
        //    }

        //}


        return true;
    }


    @Override
    public List<GpCtnLoadedVo> getCustomer(GpCtnLoadedReq gpCtnLoadedReq) {
        return this.baseMapper.getCustomer(gpCtnLoadedReq);
    }

    @Override
    public GpCtnLoaded addBatchList(GpCtnLoadedAdd gpCtnLoadedAdd) {
        GpCtnLoaded gpCtnLoaded = Convert.convert(new TypeReference<GpCtnLoaded>() {}, gpCtnLoadedAdd);
        List<GpCtnLoaded> gpCtnLoadedUpdates = gpCtnLoadedAdd.getGpCtnLoadedAddLists();
        if (CollectionUtils.isNotEmpty(gpCtnLoadedUpdates)){
            for (int i = 0; i < gpCtnLoadedUpdates.size(); i++) {
                GpCtnLoaded ctnLoaded = gpCtnLoadedUpdates.get(i);
                gpCtnLoaded = Convert.convert(new TypeReference<GpCtnLoaded>() {}, ctnLoaded);
                gpCtnLoaded.setId(null);
                gpCtnLoaded.setReceiptId(gpCtnLoadedAdd.getReceiptId());
                gpCtnLoaded.setCtnOrderId(ctnLoaded.getCtnOrderId());
                this.save(gpCtnLoaded);
                if (CollectionUtils.isNotEmpty(ctnLoaded.getPackagesInformationList())){
                    //绑定打包信息
                    this.savePackagesInformations(ctnLoaded);
                }
                if (CollectionUtils.isNotEmpty(ctnLoaded.getSackInformationList())){
                    //绑定散货信息
                    this.saveSackInformation(ctnLoaded);
                }

            }
        }
        return gpCtnLoaded;
    }

    private void savePackagesInformations(GpCtnLoaded ctnLoaded) {
        ArrayList<GpPackagesInformation> packagesInformationList = new ArrayList<>();
        List<GpPackagesInformation> list = ctnLoaded.getPackagesInformationList();
        for (GpPackagesInformation gpPackagesInformation : list) {
            //保存订单信息
            GpReceiptGoods gpReceiptGoods = iGpReceiptGoodsService.getById(gpPackagesInformation.getReceiptId());
            gpPackagesInformation.setCustomer(gpReceiptGoods.getCustomer());
            gpPackagesInformation.setCustomerTel(gpReceiptGoods.getCustomerTel());
            gpPackagesInformation.setSupplier(gpReceiptGoods.getSupplier());
            gpPackagesInformation.setSupplierTel(gpReceiptGoods.getSupplierTel());
            gpPackagesInformation.setUnit(gpReceiptGoods.getUnit());
            gpPackagesInformation.setReceiptNo(gpReceiptGoods.getReceiptNo());
            gpPackagesInformation.setHoldOrNot(gpReceiptGoods.getHoldOrNot());
            gpPackagesInformation.setCbm(gpReceiptGoods.getCbm());
            gpPackagesInformation.setRemarks(gpReceiptGoods.getRemarks());

            gpPackagesInformation.setCtnLoadedId(ctnLoaded.getId());
            gpPackagesInformation.setCtnOrderId(ctnLoaded.getCtnOrderId());
            packagesInformationList.add(gpPackagesInformation);
        }
        iGpPackagesInformationService.updateBatchById(packagesInformationList);
    }

    private void saveSackInformation(GpCtnLoaded ctnLoaded) {
        ArrayList<GpSackInformation> gpSackInformationList = new ArrayList<>();
        List<GpSackInformation> list = ctnLoaded.getSackInformationList();
        for (GpSackInformation gpSackInformation : list) {
            //保存订单信息
            GpReceiptGoods gpReceiptGoods = iGpReceiptGoodsService.getById(gpSackInformation.getReceiptId());
            gpSackInformation.setCustomer(gpReceiptGoods.getCustomer());
            gpSackInformation.setCustomerTel(gpReceiptGoods.getCustomerTel());
            gpSackInformation.setSupplier(gpReceiptGoods.getSupplier());
            gpSackInformation.setSupplierTel(gpReceiptGoods.getSupplierTel());
            gpSackInformation.setUnit(gpReceiptGoods.getUnit());
            gpSackInformation.setReceiptNo(gpReceiptGoods.getReceiptNo());
            gpSackInformation.setHoldOrNot(gpReceiptGoods.getHoldOrNot());
            gpSackInformation.setCbm(gpReceiptGoods.getCbm());
            gpSackInformation.setRemarks(gpReceiptGoods.getRemarks());

            gpSackInformation.setCtnLoadedId(ctnLoaded.getId());
            gpSackInformation.setCtnOrderId(ctnLoaded.getCtnOrderId());
            gpSackInformationList.add(gpSackInformation);
        }
        iGpSackInformationService.updateBatchById(gpSackInformationList);

    }

    @Override
    public String addbatchloaded(MultipartFile file, boolean isUpdateSupport) {

        // 导入新数据
        ExcelUtil<GpCtnLoadedExcel> util = new ExcelUtil<GpCtnLoadedExcel>(GpCtnLoadedExcel.class);
        List<GpCtnLoadedExcel> gpCtnLoadedExcels = null;
        try {
            gpCtnLoadedExcels = util.importCacheExcel(file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<GpCtnLoaded> gpCtnLoadeds = new ArrayList<>();

        for (GpCtnLoadedExcel gpCtnLoadedExcel : gpCtnLoadedExcels) {
            if (gpCtnLoadedExcel.getReceiptNo() != null) {
                GpReceiptGoods gpReceiptGoods = iGpReceiptGoodsService.getOne(new QueryWrapper<GpReceiptGoods>().eq("receipt_no", gpCtnLoadedExcel.getReceiptNo()));
                GpCtnLoaded gpCtnLoaded = Convert.convert(new TypeReference<GpCtnLoaded>() {
                }, gpReceiptGoods);
                gpCtnLoaded.setReceiptId(gpReceiptGoods.getId());
                gpCtnLoadeds.add(gpCtnLoaded);
            }
        }

        for (GpCtnLoadedExcel gpCtnLoadedExcel : gpCtnLoadedExcels) {
            if (gpCtnLoadedExcel.getAgentCtnNo() != null) {
                GpCtnOrder gpCtnOrder = iGpCtnOrderService.getOne(new QueryWrapper<GpCtnOrder>().eq("agent_ctn_no", gpCtnLoadedExcel.getAgentCtnNo()));
                GpCtnLoaded gpCtnLoaded = Convert.convert(new TypeReference<GpCtnLoaded>() {
                }, gpCtnOrder);
                gpCtnLoaded.setCtnOrderId(gpCtnOrder.getId());
                gpCtnLoadeds.add(gpCtnLoaded);
            }

        }
        String message = addbatchloadedNote(gpCtnLoadedExcels, isUpdateSupport);
        iGpCtnLoadedService.saveBatch(gpCtnLoadeds);
        return message;

    }
}
